package com.schoolhelper.controller.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.schoolhelper.model.YyzExecutors;
import com.schoolhelper.model.dao.okhttp.RefactorRequestUrl;

import com.schoolhelper.model.entity.User;
import com.schoolhelper.utils.ImageUtils;
import com.schoolhelper.utils.MyCache;
import com.schoolhelper.utils.constant.Api;

import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class AccountActivity extends AppCompatActivity implements View.OnClickListener {

    String TAG = "tag:";
    ImageView account_ic_user;
    TextView account_tv_username;
    TextView account_tv_user_description;
    TextView account_tv_credit;
    LinearLayout account_ll_favorite;
    LinearLayout account_ll_history;
    LinearLayout account_ll_following;
    LinearLayout account_ll_followed;
    LinearLayout account_ll_more_dynamics;
    LinearLayout account_ll_more_services;
    LinearLayout account_ll_more_verified;
    LinearLayout account_ll_more_settings;

    public static final String defaultIvUserImageUrl = "https://i.loli.net/2021/03/25/aDF6qK3GZBTXhLp.jpg";

    Bitmap userImageBitmap;
    String userId;
    User user;

    private BottomNavigationView mainNavigationView;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = item -> {
        Intent intent;
        switch (item.getItemId()) {
            case R.id.main_navigation_main:
                intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(0, 0);
                return true;
            case R.id.main_navigation_message:
                intent = new Intent(getApplicationContext(), ConversationListActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(0, 0);
                return true;
            case R.id.main_navigation_person:
                return false;
            default:
                Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
                return false;
        }
    };

//    SharedPreferences sp;

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);

        init();


//        String username = sp.getString("username", null);

    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1) {
            account_ic_user.setImageBitmap(ImageUtils.GetLocalOrNetBitmap(data.getStringExtra("imgUrl")));
        }
    }

    //    @RequiresApi(api = Build.VERSION_CODES.Q)
//    @Override
//    protected void onResume() {
//        super.onResume();
//        refreshProfileImg();
//    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void refreshProfileImg() {
        String getResponseJson = RefactorRequestUrl.getGetResponseJson(Api.BASE_URL, Api.USER, new HashMap<>(), userId);
        System.out.println("refreshProfileImgABC:" + getResponseJson);
//            Toast.makeText(this, getResponseJson, Toast.LENGTH_LONG).show();
        JSONObject dataJson = (JSONObject) JSONObject.parse(getResponseJson);
        dataJson = (JSONObject) dataJson.get("data");
        System.out.println("refreshProfileImgABC:" + dataJson);
        user = JSON.parseObject(String.valueOf(dataJson), User.class);
        System.out.println(user);
        //设置昵称，积分，头像
        Future<Bitmap> future = YyzExecutors.submit(() -> {
            String icUserImageUrl = user.getProfileImg();
            System.out.println("icUserImageUrl: " + icUserImageUrl);
            if (icUserImageUrl == null) {
                userImageBitmap = ImageUtils.GetLocalOrNetBitmap(defaultIvUserImageUrl);
            } else {
                userImageBitmap = ImageUtils.GetLocalOrNetBitmap(icUserImageUrl);

            }
            return userImageBitmap;
        });
        try {
            userImageBitmap = future.get();
        } catch (ExecutionException | InterruptedException e) {
            System.out.println("can't get the image");
        }

        account_ic_user.setImageBitmap(userImageBitmap);
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @SuppressLint("SetTextI18n")
    public void init() {
        account_ic_user = findViewById(R.id.account_ic_user);
        account_tv_username = (TextView) findViewById(R.id.account_tv_username);
        account_tv_user_description = (TextView) findViewById(R.id.account_tv_user_description);
        account_tv_credit = (TextView) findViewById(R.id.account_tv_credit);
        account_ll_favorite = (LinearLayout) findViewById(R.id.account_ll_favorite);
        account_ll_history = (LinearLayout) findViewById(R.id.account_ll_history);
        account_ll_following = (LinearLayout) findViewById(R.id.account_ll_following);
        account_ll_followed = (LinearLayout) findViewById(R.id.account_ll_followed);

        account_ll_more_dynamics = (LinearLayout) findViewById(R.id.account_ll_more_dynamics);
        account_ll_more_services = (LinearLayout) findViewById(R.id.account_ll_more_services);
        account_ll_more_verified = (LinearLayout) findViewById(R.id.account_ll_more_verified);
        account_ll_more_settings = (LinearLayout) findViewById(R.id.account_ll_more_settings);

        mainNavigationView = findViewById(R.id.main_bottom_view);
        mainNavigationView.setSelectedItemId(R.id.main_navigation_person);
//        sp = getSharedPreferences("userinfo", Context.MODE_PRIVATE);

        //判断登录状态
        userId = MyCache.read(getApplicationContext(), "userId");

        //200表示已登录
        if (userId != null) {
            String getResponseJson = RefactorRequestUrl.getGetResponseJson(Api.BASE_URL, Api.USER, new HashMap<>(), userId);
            System.out.println("ABC:" + getResponseJson);
//            Toast.makeText(this, getResponseJson, Toast.LENGTH_LONG).show();
            JSONObject dataJson = (JSONObject) JSONObject.parse(getResponseJson);
            dataJson = (JSONObject) dataJson.get("data");
            System.out.println("ABC:" + dataJson);
            user = JSON.parseObject(String.valueOf(dataJson), User.class);
            System.out.println(user);
            //设置昵称，积分，头像
            account_tv_username.setText(user.getUsername());
            account_tv_credit.setText("积分: " + user.getCredit());
            Future<Bitmap> future = YyzExecutors.submit(() -> {
                String icUserImageUrl = user.getProfileImg();
                System.out.println("icUserImageUrl" + icUserImageUrl);
                if (icUserImageUrl == null) {
                    userImageBitmap = ImageUtils.GetLocalOrNetBitmap(defaultIvUserImageUrl);
                } else {
                    userImageBitmap = ImageUtils.GetLocalOrNetBitmap(icUserImageUrl);

                }
                return userImageBitmap;
            });
            try {
                userImageBitmap = future.get();
            } catch (ExecutionException | InterruptedException e) {
                System.out.println("can't get the image");
            }

            account_ic_user.setImageBitmap(userImageBitmap);

        } else {
            //
            account_tv_username.setText("请登录");
            account_tv_username.setOnClickListener(this);
        }
        account_ll_favorite.setOnClickListener(this);
        account_ll_more_settings.setOnClickListener(this);

        mainNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

    @Override
    public void onClick(View view) {
        if (view == account_tv_username) {
            Intent intent = new Intent();
            intent.setClass(AccountActivity.this, LoginActivity.class);
            startActivity(intent);
        } else if (view == account_ll_favorite) {
            Log.d(TAG, "收藏");
            Toast.makeText(getApplicationContext(), "收藏", Toast.LENGTH_LONG).show();
        } else if (view == account_ll_more_settings) {
            Log.d(TAG, "onClick: 设置");
//            Intent intent = new Intent();
//            intent.setClass(AccountActivity.this, SettingActivity.class);
//            startActivity(intent);
            startActivityForResult(new Intent(getApplicationContext(), SettingActivity.class), 1);

        }
    }
}
